package com.mes.cloud.common;

import com.fasterxml.jackson.databind.JavaType;

import java.io.StringWriter;
import java.util.List;

/**
 * @Description TODO
 * @author: wxm
 * @date: 2020/1/5 15:45
 * @version: 1.0
 */
public class JsonUtil {
    private static final ExtandObjectMapper mapper = new ExtandObjectMapper();

    public JsonUtil() {
    }

    public static String obj2string(Object obj) {
        if(obj == null) {
            return "";
        } else {
            StringWriter sw = new StringWriter();

            try {
                mapper.writeValue(sw, obj);
            } catch (Exception var3) {
                throw new RuntimeException("序列化时出错:", var3);
            }

            return sw.toString();
        }
    }

    public static <T> List<T> str2list(String jsonStr, Class<T> cls) {
        List objList = null;

        try {
            JavaType t = mapper.getTypeFactory().constructParametricType(List.class, new Class[]{cls});
            objList = (List)mapper.readValue(jsonStr, t);
            return objList;
        } catch (Exception var4) {
            throw new RuntimeException("反序列化为List对象时出错:", var4);
        }
    }

    public static <T> T str2Obj(String jsonStr, Class<?> genTyClass, Class<?> cls) {
        return str2obj(jsonStr, genTyClass, cls);
    }

    public static <T> T str2obj(String jsonStr, Class<?> genTyClass, Class<?> cls) {
        Object objList = null;

        try {
            JavaType t = mapper.getTypeFactory().constructParametricType(genTyClass, new Class[]{cls});
            objList = mapper.readValue(jsonStr, t);
            return (T) objList;
        } catch (Exception var5) {
            throw new RuntimeException("反序列化为List对象时出错:", var5);
        }
    }

    public static <T> T str2obj(String jsonStr, Class<T> cls) {
        T obj = null;
        if(jsonStr != null && jsonStr.length() > 1) {
            try {
                obj = mapper.readValue(jsonStr, cls);
            } catch (Exception var4) {
                throw new RuntimeException("反序列化时出错:", var4);
            }
        }

        return obj;
    }

    public static <T> T str2obj_safe(String jsonStr, Class<T> cls) {
        T obj = null;
        if(jsonStr != null && jsonStr.length() > 1) {
            try {
                obj = mapper.readValue(jsonStr, cls);
            } catch (Exception var5) {
                ;
            }
        }

        if(obj == null) {
            try {
                obj = cls.newInstance();
            } catch (Exception var4) {
                ;
            }
        }

        return obj;
    }
}

